<template>
  <div class="container">
    <div class="header">
      <van-icon name="arrow-left" @click="$router.back()">

      </van-icon>
      登陆bilibili
      <span @click="$router.push('/')"> 返回首页</span>
    </div>
    <van-form @submit="onSubmit" ref="FormRef" :show-error-message='false' :show-error='false' @failed="onFail" validate-first>
      <van-field v-model="user.username" name="username" label="账号" placeholder="请输入您的账号" :rules="Rules.username" />
      <van-field v-model="user.password" type="password" name="password" label="密码" placeholder="请输入您的密码" :rules="Rules.password" />
      <div style="margin: 16px;">
        <div class="btn-wrap">
          <van-button type="info" @click.prevent="$router.push('/register')">
            注册
          </van-button>
          <van-button type="info">
            登陆
          </van-button>
        </div>
      </div>
    </van-form>
  </div>
</template>
<script>
import { login } from '@/api/user.js'
export default {
  data() {
    return {
      user: {
        username: 'aaa123',
        password: '123456'
      },
      Rules: {
        username: [
          { required: true, message: '请填写账号' },
          { pattern: /^.{6,15}$/, message: '姓名1-10位' }
        ],
        password: [
          { required: true, message: '请填写密码用户名' },
          { pattern: /^.{6,10}$/, message: '密码6-15位' }
        ]
      }
    }
  },
  methods: {
    onFail(err) {
      if (err.errors[0]) {
        this.$toast({ message: err.errors[0].message, position: 'top' })
      }
    },
    async onSubmit() {
      this.$toast.loading({
        message: '登陆中...',
        forbidClick: true
      })
      const { data: res } = await login(this.user)

      if (res.code !== 200) {
        return this.$toast.onFail(res.msg)
      }
      this.$store.commit('setUser', res)
      // 登录成功，跳转回原来页面
      // this.$router.back() // 先用这种方式，但是它不太好，有问题
      this.$router.push(this.$route.query.redirect || '/')
      this.$toast.success('登陆成功')
    }
  }
}
</script>
<style lang="less" scoped>
.header {
  position: relative;
  height: 46px;
  line-height: 46px;
  font-size: 18px;
  text-align: center;
  background-color: #fff;
  .van-icon {
    position: absolute;
    left: 10px;
    top: 13px;
  }
  span {
    font-size: 12px;
    position: absolute;
    top: 0;
    right: 14px;
  }
}
.van-form {
  .van-field:nth-child(1) {
    margin: 15px 0;
  }
  .btn-wrap {
    display: flex;
    justify-content: space-between;
  }
  .van-button {
    font-size: 14px;
    width: 165px;
    height: 44px;
    border-radius: 5px;
    background-color: #ffa9b5;
    border-color: #ffa9b5;
  }
  .van-button:nth-child(1) {
    background-color: transparent;
    color: #ffa9b5;
  }
}
</style>
